<template>
  <a-form ref="validateForm" :model="formData" layout="vertical">
    <a-form-item label="校验数据源">
      <a-select
        v-model="formData.validateCondition.dataSourceId"
        @change="queryDataSourceDetails($event)"
        :filter-option="false"
        @search="queryDatasourceList"
        :show-search="true"
        allow-clear
      >
        <a-option
          v-for="item in dataSourceList"
          :key="item.dataId"
          :value="item.dataId"
        >
          {{ item.dataName }}
        </a-option>
      </a-select>
      <!-- <linked-form-query :formData="formData"></linked-form-query>-->
    </a-form-item>
    <a-tabs>
      <a-tab-pane
        v-for="(groupItem, index) in formData.validateCondition.dataCondition"
        :title="`条件组${index + 1}`"
        :key="groupItem.tableQueryMappingAddDTO?.groupId || groupItem.groupId"
      >
        <a-form-item
          v-for="item in groupItem.tableQueryGroupAddDTOList"
          :key="item.groupId + item.columnKey"
          :label="`条件字段：${item.columnKey}`"
        >
          <template v-if="!item.between">
            <a-select
              v-model="item.dataIndex"
              :allow-clear="true"
              placeholder="请选择映射字段"
            >
              <a-option
                v-for="option in nameList"
                :key="option.dataIndex"
                :value="option.dataIndex"
                :disabled="
                  formData.validateCondition.dataCondition.some(
                    (e) => e.dataIndex === option.dataIndex
                  )
                "
                >{{ option.name }}</a-option
              >
            </a-select>
            <a-input
              v-model="item.defaultTheValue"
              placeholder="条件默认传参"
            ></a-input>
          </template>
          <template v-else>
            <span
              v-for="(betweenItem, betweenIndex) in item.between"
              :key="betweenItem.queryKey"
            >
              <a-select
                v-model="betweenItem.dataIndex"
                :allow-clear="true"
                :placeholder="`请选择 条件${betweenIndex + 1} 映射字段`"
              >
                <a-option
                  v-for="option in nameList"
                  :key="option.dataIndex"
                  :value="option.dataIndex"
                  :disabled="
                    formData.validateCondition.dataCondition.some(
                      (e) => e.dataIndex === option.dataIndex
                    )
                  "
                  >{{ option.name }}</a-option
                >
              </a-select>
              <a-input
                v-model="betweenItem.defaultTheValue"
                :placeholder="`条件${betweenIndex + 1}默认传参`"
              ></a-input>
            </span>
          </template>
          <a-input v-model="item.prompt" placeholder="提示语"></a-input>
        </a-form-item>
      </a-tab-pane>
    </a-tabs>
    <!--    <a-form-item-->
    <!--      v-for="item in formData.validateCondition.dataCondition"-->
    <!--      :key="item.columnKey"-->
    <!--      :label="`条件字段：${item.columnKey}`">-->
    <!--      <a-select v-model="item.dataIndex" :allowClear="true" placeholder="请选择映射字段">-->
    <!--        <a-option v-for="option in nameList" :key="option.dataIndex" :value="option.dataIndex">{{ option.name }}</a-option>-->
    <!--      </a-select>-->
    <!--      <a-input v-model="item.defaultTheValue" placeholder="输入默认值"></a-input>-->
    <!--      <a-input v-model="item.prompt" placeholder="提示语"></a-input>-->
    <!--    </a-form-item>-->
  </a-form>
</template>

<script>
import _ from "lodash";

export default {
  name: "ValidateKey",
  inject: ["dataObj"],
  props: {
    formData: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    nameList() {
      return this.dataObj.pageData
        .filter((item) => item.formData.dataIndex && item.formData.name)
        .map((item) => {
          return {
            name: item.formData.name,
            dataIndex: item.formData.dataIndex,
          };
        });
    },
  },
  data() {
    return {
      dataSourceList: [], // 数据源列表
    };
  },
  methods: {
    // 查询数据源列表
    async queryDatasourceList(dataName) {
      // try {
      //   const result = await this.$http.post(`/datasource/querySourceAllList`, {
      //     dataTypeList: ["check"],
      //     dataName: dataName || "",
      //   });
      //   const { data } = result;
      //   this.dataSourceList = data;
      // } catch (e) {
      //   console.error("请求失败", e);
      // }
    },
    // 选择了数据源，需要查询有哪些展示字段
    async queryDataSourceDetails(dataId, hold) {
      try {
        if (!dataId) {
          this.formData.validateCondition.dataCondition = [];
          return;
        }
        const result = await this.$http.get(
          "/datasource/queryDataSourceDetail",
          {
            params: {
              dataId,
            },
          }
        );
        const { data } = result;
        const { dataColumnQueryDTOList, aggregateFunctionInfoReqDTO } = data;
        const { aggregateFunctionInfoAddDTOList } =
          aggregateFunctionInfoReqDTO || {};
        const mergedList = dataColumnQueryDTOList.concat(
          aggregateFunctionInfoAddDTOList || []
        );
        // 需要根据columnKey去重后的对象数组，而不是单纯的columnKey集合，可以进一步处理：
        this.dataShowFieldOptions = mergedList.filter((item, index, self) => {
          return index === self.findIndex((t) => t.columnAs === item.columnAs);
        });
        _.assign(this.formData.validateCondition, {
          dataCondition: data.queryGroupReqDTOList?.map((item) => {
            let oldData = {};
            if (hold) {
              // 编辑时，先查找原先的值,旧模式
              oldData = this.formData.validateCondition.dataCondition?.find(
                (e) =>
                  e.groupId === item.tableQueryMappingAddDTO.groupId &&
                  e.columnKey === item.tableQueryMappingAddDTO.columnKey
              );
            }
            item.tableQueryGroupAddDTOList.forEach((queryItem) => {
              if (!_.isEmpty(oldData) && !queryItem.between) {
                queryItem.type = oldData?.type || queryItem?.type;
                queryItem.columnType =
                  oldData?.columnType || queryItem?.columnType;
                queryItem.dataIndex = oldData?.dataIndex || null;
                queryItem.defaultTheValue = oldData?.defaultTheValue || null;
                queryItem.prompt = oldData?.prompt || null;
                queryItem.columnAs = this.dataShowFieldOptions?.find(
                  (t) => t.columnKey === queryItem.queryKey
                )?.columnAs;
              } else {
                console.log(this.dataShowFieldOptions, queryItem);

                const oldV2Data = this.findMatchingQuery(
                  this.formData.validateCondition.dataCondition,
                  queryItem.groupId,
                  queryItem.queryKey
                );
                if (
                  _.isArray(queryItem.between) &&
                  queryItem.between.length &&
                  oldV2Data?.between
                ) {
                  queryItem.between[0] = oldV2Data?.between?.[0];
                  queryItem.between[1] = oldV2Data?.between?.[1];
                } else if (!_.isArray(queryItem.between)) {
                  queryItem.columnType =
                    oldV2Data?.columnType || queryItem.columnType;
                  queryItem.type = oldV2Data?.type || queryItem.type;
                  queryItem.defaultTheValue =
                    oldV2Data?.defaultTheValue || null;
                  queryItem.dataIndex = oldV2Data?.dataIndex || null;
                  queryItem.prompt = oldV2Data?.prompt || null;
                  queryItem.columnAs = this.dataShowFieldOptions?.find(
                    (t) => t.columnKey === queryItem.queryKey
                  )?.columnAs;
                }
              }
            });
            return _.cloneDeep(item);
          }),
        });
        // _.assign(this.formData.validateCondition, {
        //   dataCondition: data.queryGroupReqDTOList?.map(item => {
        //     const [condition1] = item.tableQueryGroupAddDTOList
        //     let oldData = {}
        //     if (hold) {
        //       oldData = this.formData.validateCondition.dataCondition?.find(e => e.columnKey === item.tableQueryMappingAddDTO.columnKey)
        //     }
        //     item.tableQueryMappingAddDTO.type = condition1.type
        //     item.tableQueryMappingAddDTO.columnType = condition1.columnType
        //     item.tableQueryMappingAddDTO.dataIndex = oldData?.dataIndex || undefined
        //     item.tableQueryMappingAddDTO.defaultTheValue = oldData?.defaultTheValue || undefined
        //     item.tableQueryMappingAddDTO.prompt = oldData?.prompt || undefined
        //     // 展示字段若有则寻找别名
        //     item.tableQueryMappingAddDTO.columnAs = this.dataShowFieldOptions?.find(t => t.columnKey === item.tableQueryMappingAddDTO.columnKey)?.columnAs
        //     return _.cloneDeep(item.tableQueryMappingAddDTO)
        //   })
        // })
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    findMatchingQuery(dataCondition, groupId, queryKey) {
      for (const condition of dataCondition) {
        const group = condition.tableQueryGroupAddDTOList;
        if (group) {
          for (const item of group) {
            // 查找具有指定 groupId 和 queryKey 的对象
            if (item.groupId === groupId && item.queryKey === queryKey) {
              return item;
            }
          }
        }
      }

      return null; // 如果没有找到匹配项，则返回 null
    },
  },
  created() {
    this.queryDatasourceList(); // 查询数据源列表
    const { dataSourceId } = this.formData.validateCondition;
    if (dataSourceId) {
      this.queryDataSourceDetails(dataSourceId, true);
    }
  },
};
</script>
